package com.hamizhong.iflowers.web.base;

import com.hamizhong.iflowers.common.exception.MyLoginRedirectException;
import com.hamizhong.iflowers.utils.MyConstants;
import com.hamizhong.iflowers.utils.MyErrorMsgConstants;

import net.sf.json.JSONObject;

/**
 * AJAX请求Action基类
 * 数据结构：{result:1, msg:"XXX", list:[......]}
 * result:
 * 0 - 成功
 * 1 - 失败，提示错误消息
 * 2 - 失败并且去错误页面
 * 999 - 去登录
 * @author ZhongJiang
 *
 */
public abstract class MyBaseAjaxAction extends MyBaseWebAction {
	
	@Override
	public final String execute() throws Exception {
		JSONObject result = null;
		try {
			result = doRequest();
		} catch (Exception e) {
			logger.fatal("exception -- ", e);
			if(e instanceof MyLoginRedirectException) {
				result = new JSONObject();
				result.put("result", MyConstants.AJAX_FAILED_LOGIN);
				result.put("msg", MyErrorMsgConstants.ERR_LOGIN);
				e.printStackTrace();
			}else {
				result = new JSONObject();
				result.put("result", MyConstants.AJAX_FAILED_ALERT);
				result.put("msg", MyErrorMsgConstants.ERR_SYSTEM);
				e.printStackTrace();
			}
		}
		getRP().setContentType("application/json;charset=utf-8");
		getPW().write(result.toString());
		return null;
	}

	protected abstract JSONObject doRequest();
	
	
}
